package com.superquan.selfstudybootmybatis.utils.email;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;

/**
 * 邮件发送工具类
 */
@Slf4j
@PropertySource("classpath:application-dev.yml")
public class SendEmailUtil {
    private static JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private static String SENDER;
    // 服务器
    private static String ALIDM_SMTP_HOST ;
    // 端口
    private static int ALIDM_SMTP_PORT;
    // 阿里云的smtp推送 账户 ：阿里云邮件推送控制台配置的的发新地址
    private static String ALIYUN_EMAIL;
    // 密码：设置的SMTP密码
    private static String ALIYUN_EMAIL_PWD;
    //发件人
    private static String NICK;
    private static String consumerQueue ;
    private static String sysName;

    public SendEmailUtil(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    /**
     * 发送普通邮件
     * @param receiver 收件人
     * @param subject 邮件标题
     * @param content 邮件内容
     * @return
     */
    public static String sendSimpleMailMessage(String receiver,String subject,String content){
        try{
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setFrom(SENDER);
            mailMessage.setTo(receiver);
            mailMessage.setSubject(subject);
            mailMessage.setText(content);
            mailMessage.setSentDate(new Date());
            mailSender.send(mailMessage);
        }catch (Exception e){
            e.printStackTrace();
            return "邮件发送异常！";
        }
        return "邮件发送成功！";
    }
    /**
     * @param title   邮件标题
     * @param content 邮件内容
     * @param emails  收件人邮箱
     * @throws MessagingException
     */
    public static JSONObject aliSendMail(String title, String content,
                                         String emails) {
        // 发送信息返回json
        JSONObject josn = new JSONObject();
        boolean b = true;
        // 配置发送邮件的环境属性
        final Properties props = new Properties();
        // 表示SMTP发送邮件，需要进行身份验证
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", ALIDM_SMTP_HOST);
        props.put("mail.smtp.port", ALIDM_SMTP_PORT);
        props.put("mail.smtp.starttls.enable", "true");
//		props.put("mail.smtp.localhost", "127.0.0.1");
        // 如果使用ssl，则去掉使用25端口的配置，进行如下配置,
//		 props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
//		 props.put("mail.smtp.socketFactory.port", "465");
//		 props.put("mail.smtp.port", "465");
        // 发件人的账号
        props.put("mail.user", ALIYUN_EMAIL);
        // 访问SMTP服务时需要提供的密码
        props.put("mail.password", ALIYUN_EMAIL_PWD);
        // 构建授权信息，用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息，创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // mailSession.setDebug(true);
        // 创建邮件消息
        //消息日志ID，消费队列时候使用
        String messageLogId = UUID.randomUUID().toString().replaceAll("-", "");
        final String messageIDValue = "<" + messageLogId + "_" + sysName + "_" + consumerQueue + ">";
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession) {
            protected void updateMessageID() throws MessagingException {
                //设置自定义Message-ID值，设置一个消费ID
                setHeader("Message-ID", messageIDValue);
            }
        };
        log.info("Message-ID:" + messageIDValue + "，sys:" + sysName + "，queue:" + consumerQueue + ":" + emails + "，messageLogId:" + messageLogId);

        // 设置发件人
        try {
            String nick = javax.mail.internet.MimeUtility.encodeText(NICK);
//			from = new InternetAddress(ALIYUN_EMAIL);
            message.setFrom(new InternetAddress(nick + " <" + ALIYUN_EMAIL + ">"));
//			Address[] a = new Address[1];
//			a[0] = new InternetAddress(ALIYUN_EMAIL);
//			message.setReplyTo(a);
            // 设置收件人
            InternetAddress to = new InternetAddress(emails);
            message.setRecipient(MimeMessage.RecipientType.TO, to);
            // 设置邮件标题
            message.setSubject(title);
            // 设置邮件的内容体
            message.setContent(content, "text/html;charset=UTF-8");
            // 发送邮件
            Transport.send(message);
        } catch (MessagingException e) {

            josn.put("code", "error");//失败
            josn.put("des", "MessagingException异常");
            log.error("MessagingException异常");
            b = false;
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {

            josn.put("code", "error");//失败
            josn.put("des", "UnsupportedEncodingException异常");
            log.error("UnsupportedEncodingException异常");
            b = false;
            e.printStackTrace();
        } finally {
            if (b) {
                josn.put("code", "OK");//成功
                josn.put("des", "OK");
            }
            //消费ID,作为日志ID，供队列消费使用，（阿里云队列只能消费一次）
            josn.put("messageLogId", messageLogId);
        }
        return josn;
    }
}
